<?php
namespace App\Services\Tools;

use App\Exceptions\BasicException;

class CurlService
{
    /**
     * Curl GET请求方法
     * @param $url  //请求地址
     * @param array $get_data   get请求数据
     * @return mixed
     * @throws BasicException
     */
    static function curl_get($url,$get_data=array())
    {
        //构造请求参数
        $param = http_build_query($get_data);
        $url .= '?'.$param;
        //初始化
        $ch = curl_init();

        curl_setopt($ch,CURLOPT_URL,$url);

        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);

        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);

        $output = curl_exec($ch);

        $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        if($code != 200) throw new BasicException(10020);

        curl_close($ch);

        return json_decode($output);
    }

    static function curl_get_info($url, $params, $headers)
    {
        $headers = array_merge($headers, ['Accept-Charset: EUC-CN']);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        $info = curl_exec($ch);
        $statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        if ($statusCode == 200) {
            $encoding = mb_detect_encoding($info, "UTF-8,GB2312,GBK");
            $info = json_decode(mb_convert_encoding($info, 'UTF-8', $encoding), true);
        } else {
            $info = [];
        }
        return $info;
    }

}
